package com.olclass.web.service;

import com.olclass.web.dao.LessonItemRepository;
import com.olclass.web.dao.LessonMediaRepository;
import com.olclass.web.dao.LessonRepository;
import com.olclass.web.dao.UserRepository;
import com.olclass.web.domain.College;
import com.olclass.web.domain.Lesson;
import com.olclass.web.domain.Lessonitem;
import com.olclass.web.domain.Lessonmedia;
import com.olclass.web.support.QueryParamUtil;
import com.olclass.web.support.QuerySpecification;
import com.vividsolutions.jts.geom.Geometry;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * FileName: CollegeService.java
 * Author:   Administrator
 * Date:     2021/3/23 19:12
 * Description:
 */

@Service
@Transactional
public class LessonService {

    @Value("#{imeSettings['project.uploadDir']}")
    protected String uploadDir;

    @Autowired
    LessonRepository repository;

    @Autowired
    LessonMediaRepository mediaRepository;

    @Autowired
    LessonItemRepository itemRepository;

    public Page<Lesson> queryByFilter(String filterParam, String sortParam, int start, int limit) {
        Page<Lesson> results = repository.findAll(new QuerySpecification<Lesson>(filterParam),
                new PageRequest(start, limit, QueryParamUtil.parseSortParams(sortParam)));
        return results;
    }

    public void save(Lesson item) {
        repository.save(item);
    }

    public void delete(String id) {
        repository.delete(id);
    }

    public Lesson findById(String id) {
        return repository.findById(id);
    }

    public void saveLessonItem(Lessonitem item) {
        itemRepository.save(item);
    }
    public Lessonitem findOneLessonItem(String id){
        return itemRepository.findOne(id);
    }
    public Lessonmedia findOneLessonMedia(String id){
        return mediaRepository.findOne(id);
    }
    public void deleteLessonItem(String id) {
        itemRepository.delete(id);
    }

    public void deleteLessonMeida(String id) {
        mediaRepository.delete(id);
    }

    public void importTaskFile(HttpServletRequest request, String lessonitem, String userId) throws Exception{
        HttpSession session = request.getSession();
        String uploadDir =session.getServletContext().getRealPath(File.separator);
        File dir = new File(uploadDir+"/upload/" + userId);
        if(!dir.exists()){
            dir.mkdirs();
        }
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String key = iter.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    String fileName = multipartFile.getOriginalFilename();
                    String subfix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    Integer type = getFileType(subfix);

                    long size = multipartFile.getSize();
                    String date = sdf.format(new Date()).toString();
                    File file = new File(dir, fileName);
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
                    String url = userId + "/" + fileName;

                    Lessonmedia lessonmedia = new Lessonmedia();
                    lessonmedia.setDate(date);
                    lessonmedia.setUrl(url);
                    lessonmedia.setFilesize(size);
                    lessonmedia.setLessonid(lessonitem);
                    lessonmedia.setName(fileName);
                    lessonmedia.setUserid(userId);
                    lessonmedia.setType(type);
                    mediaRepository.save(lessonmedia);
                }
            }
        }
    }

    private Integer getFileType(String subfix) {

        List<String> image = Arrays.asList("png", "jpg", "jpeg", "gif", "ico", "bmp", "pic", "tif");
        List<String> video = Arrays.asList("mp4", "webm", "avi", "rmvb", "3gp", "flv");
        List<String> pdf = Arrays.asList("pdf");
        List<String> audio = Arrays.asList("mp3", "ogg", "wav", "acc", "vorbis", "silk");
        List<String> zip = Arrays.asList("zip","rar");
        if(image.contains(subfix)){
            return 0;
        }else if(video.contains(subfix)){
            return 1;
        }else if(pdf.contains(subfix)){
            return 2;
        }else if(audio.contains(subfix)){
            return 3;
        }else if(zip.contains(subfix)){
            return 4;
        }else {
            return 5;
        }


    }
}